"""
身份证双面处理器 - 主界面

身份证照片自动处理器的图形用户界面
核心功能：身份证正反面处理与组合排版
"""

import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import threading
import os
import sys
import queue
from PIL import Image, ImageTk

# 添加父目录到路径，以便导入src模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.id_card_processor import IDCardProcessor


class MainWindow:
    """
    身份证双面处理器主窗口
    
    功能：
    - 身份证正面（人像面）选择
    - 身份证反面（国徽面）选择
    - 双面组合处理
    - 参数配置
    - 进度显示和状态监控
    - 结果预览和保存
    """
    
    def __init__(self):
        """初始化主窗口"""
        self.root = tk.Tk()
        self.processor = IDCardProcessor()
        self.message_queue = queue.Queue()
        
        # 文件路径
        self.front_path = ""
        self.back_path = ""
        self.output_path = ""
        
        # 处理状态
        self.processing = False
        
        # 窗口基本设置
        self.setup_window()
        
        # 创建界面组件
        self.create_widgets()
        
        # 启动消息检查
        self.check_messages()
    
    def setup_window(self):
        """
        设置主窗口属性
        
        功能：
        - 窗口标题、大小、图标
        - 窗口居中显示
        - 禁止调整大小
        """
        self.root.title("身份证双面处理器 v1.0")
        self.root.geometry("750x650")
        self.root.resizable(False, False)
        
        # 窗口居中
        self.center_window()
        
        # 设置窗口图标（如果有的话）
        try:
            self.root.iconbitmap("icon.ico")
        except:
            pass
    
    def center_window(self):
        """将窗口居中显示"""
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f"{width}x{height}+{x}+{y}")
    
    def create_menu(self):
        """创建菜单栏"""
        menubar = tk.Menu(self.root)
        self.root.config(menu=menubar)
        
        # 文件菜单
        file_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="文件", menu=file_menu)
        file_menu.add_command(label="打开示例", command=self.load_sample_images)
        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.root.quit)
        
        # 工具菜单
        tools_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="工具", menu=tools_menu)
        tools_menu.add_command(label="批量处理", command=self.batch_processing)
        tools_menu.add_command(label="PDF导出", command=self.export_pdf)
        
        # 帮助菜单
        help_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="帮助", menu=help_menu)
        help_menu.add_command(label="使用说明", command=self.show_usage_guide)
        help_menu.add_command(label="关于", command=self.show_about)
    
    def show_about(self):
        """显示关于对话框"""
        messagebox.showinfo("关于", 
                           "身份证双面处理器 v1.0\n\n"
                           "专业的身份证照片处理工具\n\n"
                           "核心功能：\n"
                           "• 身份证正面（人像面）处理\n"
                           "• 身份证反面（国徽面）处理\n"
                           "• 自动抠图去背景\n"
                           "• 智能校正倾斜\n"
                           "• A4复印件效果\n"
                           "• 高质量PDF导出\n\n"
                           "支持批量处理和自定义参数配置")
    
    def show_usage_guide(self):
        """显示使用说明"""
        guide_text = """身份证双面处理器使用说明

1. 选择身份证图片：
   • 正面（人像面）：包含照片和个人信息的一面
   • 反面（国徽面）：包含国徽和签发机关的一面

2. 处理选项：
   • 自动校正倾斜：自动检测并校正图片倾斜
   • 增强对比度：提升图片清晰度和对比度
   • 添加阴影效果：模拟真实复印件效果
   • 模拟扫描效果：添加扫描纹理和轻微噪点

3. 输出设置：
   • 输出质量：60%-100%，推荐95%
   • 自动生成A4排版（正面在上，反面在下）

4. 批量处理：
   • 可同时处理多对身份证图片
   • 自动匹配正反面（按文件名）

注意事项：
- 支持JPG、PNG、BMP等常见格式
- 建议使用高清晰度原图
- 处理时间取决于图片大小和质量"""
        
        # 创建使用说明窗口
        guide_window = tk.Toplevel(self.root)
        guide_window.title("使用说明")
        guide_window.geometry("500x400")
        guide_window.resizable(False, False)
        
        text_widget = scrolledtext.ScrolledText(guide_window, wrap=tk.WORD, 
                                               font=("微软雅黑", 10))
        text_widget.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        text_widget.insert(tk.END, guide_text)
        text_widget.config(state=tk.DISABLED)
    
    def create_widgets(self):
        """
        创建界面组件
        
        组件包括：
        - 菜单栏
        - 身份证图片选择区域
        - 参数配置区域
        - 控制按钮
        - 状态显示
        """
        # 创建菜单栏
        self.create_menu()
        
        # 主容器
        main_frame = ttk.Frame(self.root, padding="15")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 身份证图片选择区域
        self.create_id_card_section(main_frame)
        
        # 参数配置区域
        self.create_config_section(main_frame)
        
        # 控制按钮区域
        self.create_control_section(main_frame)
        
        # 状态和日志区域
        self.create_status_section(main_frame)
        
        # 配置列权重
        main_frame.columnconfigure(0, weight=1)
    
    def create_id_card_section(self, parent):
        """
        创建身份证图片选择区域
        
        参数:
            parent: 父容器
        """
        id_frame = ttk.LabelFrame(parent, text="身份证图片选择", padding="15")
        id_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
        
        # 正面图片选择
        ttk.Label(id_frame, text="正面（人像面）:", font=("微软雅黑", 10)).grid(
            row=0, column=0, sticky=tk.W, pady=(0, 8))
        
        front_frame = ttk.Frame(id_frame)
        front_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, 20))
        
        self.front_entry = ttk.Entry(front_frame, width=55, font=("微软雅黑", 9))
        self.front_entry.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
        
        ttk.Button(front_frame, text="选择正面", 
                  command=self.browse_front_image).grid(row=0, column=1)
        
        # 反面图片选择
        ttk.Label(id_frame, text="反面（国徽面）:", font=("微软雅黑", 10)).grid(
            row=2, column=0, sticky=tk.W, pady=(0, 8))
        
        back_frame = ttk.Frame(id_frame)
        back_frame.grid(row=3, column=0, sticky=(tk.W, tk.E), pady=(0, 20))
        
        self.back_entry = ttk.Entry(back_frame, width=55, font=("微软雅黑", 9))
        self.back_entry.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
        
        ttk.Button(back_frame, text="选择反面", 
                  command=self.browse_back_image).grid(row=0, column=1)
        
        # 输出文件
        ttk.Label(id_frame, text="保存位置:", font=("微软雅黑", 10)).grid(
            row=4, column=0, sticky=tk.W, pady=(0, 8))
        
        output_frame = ttk.Frame(id_frame)
        output_frame.grid(row=5, column=0, sticky=(tk.W, tk.E))
        
        self.output_entry = ttk.Entry(output_frame, width=55, font=("微软雅黑", 9))
        self.output_entry.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
        
        ttk.Button(output_frame, text="保存为", 
                  command=self.browse_output_file).grid(row=0, column=1)
        
        # 配置列权重
        id_frame.columnconfigure(0, weight=1)
        front_frame.columnconfigure(0, weight=1)
        back_frame.columnconfigure(0, weight=1)
        output_frame.columnconfigure(0, weight=1)
    
    def create_config_section(self, parent):
        """
        创建参数配置区域
        
        参数:
            parent: 父容器
        """
        config_frame = ttk.LabelFrame(parent, text="处理选项", padding="15")
        config_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
        
        # 创建两列布局
        left_frame = ttk.Frame(config_frame)
        left_frame.grid(row=0, column=0, sticky=(tk.W, tk.N), padx=(0, 30))
        
        right_frame = ttk.Frame(config_frame)
        right_frame.grid(row=0, column=1, sticky=(tk.W, tk.N))
        
        # 左列选项
        self.auto_correct_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(left_frame, text="自动校正倾斜", 
                       variable=self.auto_correct_var).grid(row=0, column=0, sticky=tk.W, pady=2)
        
        self.enhance_contrast_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(left_frame, text="增强对比度", 
                       variable=self.enhance_contrast_var).grid(row=1, column=0, sticky=tk.W, pady=2)
        
        # 右列选项
        self.add_shadow_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(right_frame, text="添加阴影效果", 
                       variable=self.add_shadow_var).grid(row=0, column=0, sticky=tk.W, pady=2)
        
        self.scan_artifacts_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(right_frame, text="模拟扫描效果", 
                       variable=self.scan_artifacts_var).grid(row=1, column=0, sticky=tk.W, pady=2)
        
        # 输出质量设置
        quality_frame = ttk.Frame(config_frame)
        quality_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(20, 0))
        
        ttk.Label(quality_frame, text="输出质量:", font=("微软雅黑", 10)).grid(
            row=0, column=0, sticky=tk.W)
        
        self.quality_var = tk.IntVar(value=95)
        quality_scale = ttk.Scale(quality_frame, from_=60, to=100, 
                                 variable=self.quality_var, orient=tk.HORIZONTAL, length=200)
        quality_scale.grid(row=0, column=1, padx=(15, 15))
        
        self.quality_label = ttk.Label(quality_frame, text="95%", font=("微软雅黑", 10))
        self.quality_label.grid(row=0, column=2)
        quality_scale.configure(command=self.update_quality_label)
        
        # 配置列权重
        config_frame.columnconfigure(0, weight=1)
        config_frame.columnconfigure(1, weight=1)
        quality_frame.columnconfigure(1, weight=1)
    
    def create_control_section(self, parent):
        """创建控制按钮区域"""
        control_frame = ttk.Frame(parent)
        control_frame.grid(row=2, column=0, pady=(0, 15))
        
        # 主要按钮
        self.process_btn = ttk.Button(control_frame, text="开始处理身份证双面", 
                                     command=self.start_processing, 
                                     style="Accent.TButton")
        self.process_btn.grid(row=0, column=0, padx=(0, 10))
        
        # 其他按钮
        ttk.Button(control_frame, text="预览效果", 
                  command=self.preview_image).grid(row=0, column=1, padx=(0, 10))
        
        ttk.Button(control_frame, text="清空选择", 
                  command=self.clear_selection).grid(row=0, column=2)
    
    def create_status_section(self, parent):
        """创建状态和日志区域"""
        status_frame = ttk.LabelFrame(parent, text="处理状态", padding="10")
        status_frame.grid(row=3, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 0))
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(status_frame, variable=self.progress_var, 
                                          maximum=100, length=400)
        self.progress_bar.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 状态标签
        self.status_label = ttk.Label(status_frame, text="就绪", 
                                     font=("微软雅黑", 9), foreground="green")
        self.status_label.grid(row=1, column=0, sticky=tk.W, pady=(0, 10))
        
        # 日志文本框
        log_frame = ttk.Frame(status_frame)
        log_frame.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        self.log_text = scrolledtext.ScrolledText(log_frame, height=8, width=80,
                                                 font=("微软雅黑", 9))
        self.log_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置权重
        status_frame.columnconfigure(0, weight=1)
        status_frame.rowconfigure(2, weight=1)
        log_frame.columnconfigure(0, weight=1)
        log_frame.rowconfigure(0, weight=1)
        parent.rowconfigure(3, weight=1)
    
    def update_quality_label(self, value):
        """更新质量标签显示"""
        self.quality_label.config(text=f"{int(float(value))}%")
    
    def browse_front_image(self):
        """选择正面图片"""
        file_types = [
            ("图片文件", "*.jpg *.jpeg *.png *.bmp *.tiff"),
            ("所有文件", "*.*")
        ]
        
        filename = filedialog.askopenfilename(
            title="选择身份证正面图片",
            filetypes=file_types
        )
        
        if filename:
            self.front_entry.delete(0, tk.END)
            self.front_entry.insert(0, filename)
            self.front_path = filename
            self.log_message(f"已选择正面图片: {os.path.basename(filename)}")
            
            # 如果已选择反面，自动生成输出路径
            if self.back_path:
                self.auto_generate_output_path()
    
    def browse_back_image(self):
        """选择反面图片"""
        file_types = [
            ("图片文件", "*.jpg *.jpeg *.png *.bmp *.tiff"),
            ("所有文件", "*.*")
        ]
        
        filename = filedialog.askopenfilename(
            title="选择身份证反面图片",
            filetypes=file_types
        )
        
        if filename:
            self.back_entry.delete(0, tk.END)
            self.back_entry.insert(0, filename)
            self.back_path = filename
            self.log_message(f"已选择反面图片: {os.path.basename(filename)}")
            
            # 如果已选择正面，自动生成输出路径
            if self.front_path:
                self.auto_generate_output_path()
    
    def browse_output_file(self):
        """选择输出文件"""
        filename = filedialog.asksaveasfilename(
            title="保存处理结果",
            defaultextension=".jpg",
            filetypes=[("JPEG文件", "*.jpg"), ("PNG文件", "*.png"), ("所有文件", "*.*")]
        )
        
        if filename:
            self.output_entry.delete(0, tk.END)
            self.output_entry.insert(0, filename)
            self.output_path = filename
    
    def clear_selection(self):
        """清空所有选择"""
        self.front_entry.delete(0, tk.END)
        self.back_entry.delete(0, tk.END)
        self.output_entry.delete(0, tk.END)
        self.front_path = ""
        self.back_path = ""
        self.output_path = ""
        self.log_message("已清空所有选择")
    
    def auto_generate_output_path(self):
        """自动生成输出路径"""
        if self.front_path and self.back_path:
            # 基于正面图片路径生成输出文件名
            base_dir = os.path.dirname(self.front_path)
            base_name = os.path.splitext(os.path.basename(self.front_path))[0]
            output_filename = f"{base_name}_身份证双面.jpg"
            output_path = os.path.join(base_dir, output_filename)
            
            self.output_entry.delete(0, tk.END)
            self.output_entry.insert(0, output_path)
            self.output_path = output_path
    
    def load_sample_images(self):
        """加载示例图片（如果有的话）"""
        messagebox.showinfo("提示", "示例图片功能待开发")
    
    def preview_image(self):
        """预览处理效果（不保存文件）"""
        if not self.front_path or not self.back_path:
            messagebox.showwarning("警告", "请先选择正面和反面图片")
            return
        
        messagebox.showinfo("提示", "预览功能待开发\n将显示处理后的效果预览")
    
    def start_processing(self):
        """开始处理身份证双面"""
        if not self.front_path or not self.back_path:
            messagebox.showwarning("警告", "请选择正面和反面图片")
            return
        
        if not self.output_path:
            # 自动生成输出路径
            self.auto_generate_output_path()
            
        if self.processing:
            messagebox.showwarning("警告", "正在处理中，请稍等...")
            return
        
        # 准备处理配置
        config = {
            'auto_correct': self.auto_correct_var.get(),
            'enhance_contrast': self.enhance_contrast_var.get(),
            'add_shadow': self.add_shadow_var.get(),
            'scan_artifacts': self.scan_artifacts_var.get(),
            'output_quality': self.quality_var.get()
        }
        
        # 启动处理线程
        self.processing = True
        self.process_btn.config(state="disabled", text="处理中...")
        self.progress_var.set(0)
        
        thread = threading.Thread(target=self.process_image_thread, args=(config,))
        thread.daemon = True
        thread.start()
    
    def process_image_thread(self, config):
        """处理图像的线程函数"""
        try:
            self.message_queue.put(("status", "开始处理身份证双面...", "info"))
            self.message_queue.put(("progress", 10))
            
            # 处理身份证双面
            success = self.processor.process_front_back(
                self.front_path, 
                self.back_path, 
                self.output_path, 
                config
            )
            
            self.message_queue.put(("progress", 100))
            
            if success:
                self.message_queue.put(("status", "处理完成！", "success"))
                self.message_queue.put(("result", self.output_path))
            else:
                self.message_queue.put(("status", "处理失败", "error"))
                self.message_queue.put(("error", "身份证双面处理失败"))
                
        except Exception as e:
            self.message_queue.put(("status", f"处理错误: {e}", "error"))
            self.message_queue.put(("error", str(e)))
        finally:
            self.message_queue.put(("processing_done",))
    
    def batch_processing(self):
        """批量处理"""
        try:
            batch_window = BatchWindow(self.root, self.processor)
        except Exception as e:
            messagebox.showerror("错误", f"无法打开批量处理窗口: {e}")
    
    def export_pdf(self):
        """导出PDF"""
        if not self.output_path or not os.path.exists(self.output_path):
            messagebox.showwarning("警告", "请先处理图片再导出PDF")
            return
        
        pdf_path = filedialog.asksaveasfilename(
            title="保存PDF文件",
            defaultextension=".pdf",
            filetypes=[("PDF文件", "*.pdf"), ("所有文件", "*.*")]
        )
        
        if pdf_path:
            try:
                # 使用layout_generator导出PDF
                from src.pdf_exporter import PDFExporter
                exporter = PDFExporter()
                exporter.export_single_image(self.output_path, pdf_path)
                messagebox.showinfo("成功", f"PDF已保存到: {pdf_path}")
            except Exception as e:
                messagebox.showerror("错误", f"PDF导出失败: {e}")
    
    def check_messages(self):
        """检查消息队列并更新UI"""
        try:
            while True:
                message = self.message_queue.get_nowait()
                msg_type = message[0]
                
                if msg_type == "status":
                    self.update_status(message[1], message[2] if len(message) > 2 else "info")
                elif msg_type == "progress":
                    self.progress_var.set(message[1])
                elif msg_type == "log":
                    self.log_message(message[1], message[2] if len(message) > 2 else "info")
                elif msg_type == "result":
                    self.show_result_dialog(message[1])
                elif msg_type == "error":
                    messagebox.showerror("错误", message[1])
                elif msg_type == "processing_done":
                    self.processing = False
                    self.process_btn.config(state="normal", text="开始处理身份证双面")
                    
        except queue.Empty:
            pass
        
        # 继续检查消息
        self.root.after(100, self.check_messages)
    
    def log_message(self, message, level="info"):
        """
        添加日志消息
        
        参数:
            message: 消息内容
            level: 消息级别 (info, warning, error, success)
        """
        import datetime
        timestamp = datetime.datetime.now().strftime("%H:%M:%S")
        
        # 根据级别设置颜色标记
        if level == "error":
            prefix = "[错误]"
        elif level == "warning":
            prefix = "[警告]"
        elif level == "success":
            prefix = "[成功]"
        else:
            prefix = "[信息]"
        
        log_entry = f"{timestamp} {prefix} {message}\n"
        
        self.log_text.insert(tk.END, log_entry)
        self.log_text.see(tk.END)  # 自动滚动到最新消息
    
    def update_status(self, message, level="info"):
        """
        更新状态标签
        
        参数:
            message: 状态消息
            level: 消息级别
        """
        color_map = {
            "info": "blue",
            "success": "green", 
            "warning": "orange",
            "error": "red"
        }
        
        color = color_map.get(level, "black")
        self.status_label.config(text=message, foreground=color)
        self.log_message(message, level)
    
    def show_result_dialog(self, output_path):
        """显示处理结果对话框"""
        result = messagebox.askyesno(
            "处理完成", 
            f"身份证双面处理完成！\n\n输出文件: {output_path}\n\n是否打开文件所在文件夹？"
        )
        
        if result:
            try:
                os.startfile(os.path.dirname(output_path))
            except:
                messagebox.showinfo("提示", f"请手动打开文件夹: {os.path.dirname(output_path)}")
    
    def run(self):
        """运行应用程序"""
        self.log_message("身份证双面处理器已启动")
        self.root.mainloop()


class BatchWindow:
    """批量处理窗口"""
    
    def __init__(self, parent, processor):
        """初始化批量处理窗口"""
        self.window = tk.Toplevel(parent)
        self.window.title("批量处理")
        self.window.geometry("600x400")
        self.window.resizable(False, False)
        self.window.grab_set()  # 模态窗口
        
        self.processor = processor
        self.processing = False
        
        # 居中显示
        self.center_window()
        
        # 创建界面
        self.create_widgets()
    
    def center_window(self):
        """窗口居中显示"""
        self.window.update_idletasks()
        width = self.window.winfo_width()
        height = self.window.winfo_height()
        x = (self.window.winfo_screenwidth() // 2) - (width // 2)
        y = (self.window.winfo_screenheight() // 2) - (height // 2)
        self.window.geometry(f"{width}x{height}+{x}+{y}")
    
    def create_widgets(self):
        """创建批量处理界面组件"""
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 文件夹选择
        folder_frame = ttk.LabelFrame(main_frame, text="文件夹选择", padding="15")
        folder_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 20))
        
        ttk.Label(folder_frame, text="输入文件夹:").grid(row=0, column=0, sticky=tk.W, pady=(0, 10))
        
        input_frame = ttk.Frame(folder_frame)
        input_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
        
        self.input_folder_entry = ttk.Entry(input_frame, width=50)
        self.input_folder_entry.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
        
        ttk.Button(input_frame, text="选择文件夹", 
                  command=self.browse_input_folder).grid(row=0, column=1)
        
        ttk.Label(folder_frame, text="输出文件夹:").grid(row=2, column=0, sticky=tk.W, pady=(0, 10))
        
        output_frame = ttk.Frame(folder_frame)
        output_frame.grid(row=3, column=0, sticky=(tk.W, tk.E))
        
        self.output_folder_entry = ttk.Entry(output_frame, width=50)
        self.output_folder_entry.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
        
        ttk.Button(output_frame, text="选择文件夹", 
                  command=self.browse_output_folder).grid(row=0, column=1)
        
        # 控制按钮
        control_frame = ttk.Frame(main_frame)
        control_frame.grid(row=1, column=0, pady=(0, 20))
        
        self.batch_btn = ttk.Button(control_frame, text="开始批量处理", 
                                   command=self.start_batch_processing)
        self.batch_btn.grid(row=0, column=0, padx=(0, 10))
        
        ttk.Button(control_frame, text="关闭", 
                  command=self.window.destroy).grid(row=0, column=1)
        
        # 状态显示
        status_frame = ttk.LabelFrame(main_frame, text="处理状态", padding="10")
        status_frame.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        self.batch_progress = ttk.Progressbar(status_frame, length=400)
        self.batch_progress.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        self.batch_status = ttk.Label(status_frame, text="就绪")
        self.batch_status.grid(row=1, column=0, sticky=tk.W)
        
        # 配置权重
        folder_frame.columnconfigure(0, weight=1)
        input_frame.columnconfigure(0, weight=1)
        output_frame.columnconfigure(0, weight=1)
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(2, weight=1)
        status_frame.columnconfigure(0, weight=1)
        self.window.columnconfigure(0, weight=1)
        self.window.rowconfigure(0, weight=1)
    
    def browse_input_folder(self):
        """选择输入文件夹"""
        folder = filedialog.askdirectory(title="选择包含身份证图片的文件夹")
        if folder:
            self.input_folder_entry.delete(0, tk.END)
            self.input_folder_entry.insert(0, folder)
    
    def browse_output_folder(self):
        """选择输出文件夹"""
        folder = filedialog.askdirectory(title="选择处理结果保存文件夹")
        if folder:
            self.output_folder_entry.delete(0, tk.END)
            self.output_folder_entry.insert(0, folder)
    
    def start_batch_processing(self):
        """开始批量处理"""
        input_folder = self.input_folder_entry.get().strip()
        output_folder = self.output_folder_entry.get().strip()
        
        if not input_folder or not output_folder:
            messagebox.showwarning("警告", "请选择输入和输出文件夹")
            return
        
        if not os.path.exists(input_folder):
            messagebox.showerror("错误", "输入文件夹不存在")
            return
        
        if self.processing:
            messagebox.showwarning("警告", "正在处理中...")
            return
        
        # 启动批量处理线程
        self.processing = True
        self.batch_btn.config(state="disabled", text="处理中...")
        
        thread = threading.Thread(target=self.batch_process_thread, 
                                 args=(input_folder, output_folder))
        thread.daemon = True
        thread.start()
    
    def batch_process_thread(self, input_folder, output_folder):
        """批量处理线程"""
        try:
            # 这里应该实现批量处理逻辑
            # 扫描文件夹，匹配正反面图片，批量处理
            messagebox.showinfo("提示", "批量处理功能待完善")
        except Exception as e:
            messagebox.showerror("错误", f"批量处理失败: {e}")
        finally:
            self.processing = False
            self.batch_btn.config(state="normal", text="开始批量处理") 